package com.sanyue.imitation;

import org.junit.Test;

/**
 * @author sanyue
 * @version 1.0
 * @description: TODO-2
 * @date 2022/1/22 下午5:27
 */
public class TwoAdd {

    @Test
    public void solve() {
        ListNode l1 = new ListNode(9);
        l1.next = new ListNode(9);

        ListNode l2 = new ListNode(9);
        l2.next = new ListNode(9);
        l2.next.next = new ListNode(9);
        ListNode ans = addTwoNumbers(l1, l2);
        while (ans != null){
            System.out.println(ans.val);
            ans = ans.next;
        }
    }
    //在所有 Java 提交中击败了100.00%的用户
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode ans = new ListNode();
        ListNode anss = ans;
        int flag = 0;
        while (l1 != null || l2 != null){
            int a = l1 == null ? 0 : l1.val;
            int b = l2 == null ? 0 : l2.val;
            int sum = (a + b + flag)%10;
            ListNode l3 = new ListNode(sum);
            flag = (a + b + flag)/10;
            ans.next = l3;
            ans = ans.next;
            if (l1 != null) l1 = l1.next;
            if (l2 != null) l2 = l2.next;
        }
        if (flag != 0)ans.next = new ListNode(flag);
        return  anss.next;
    }

}

  //Definition for singly-linked list.
  class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  }
